package cn.ctbu.simple_score_manage.api;

import cn.ctbu.simple_score_manage.common.R;
import cn.ctbu.simple_score_manage.common.REnum;
import cn.ctbu.simple_score_manage.common.RunException;
import cn.ctbu.simple_score_manage.domain.Course;
import cn.ctbu.simple_score_manage.domain.Teacher;
import cn.ctbu.simple_score_manage.service.ICourseService;
import cn.ctbu.simple_score_manage.service.ITeacherService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/course")
public class CourseController {
    @Autowired
    ITeacherService teacherService;
    @Autowired
    ICourseService courseService;

    @PostMapping
    public R addClass(@RequestBody JSONObject jsonObject) throws RunException {
        try {
            Integer teacherId = Integer.parseInt(String.valueOf(jsonObject.get("teacherId")) );
            String no = (String) jsonObject.get("no");
            String name = (String) jsonObject.get("name");
            Float credit = Float.parseFloat(String.valueOf(jsonObject.get("credit")));
            String type = (String) jsonObject.get("type");
            Course course = new Course();
            course.setNo(no);
            course.setCredit(credit);
            course.setName(name);
            course.setType(type);
            //检查是否有重复的课程号
            LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Course::getNo, course.getNo());
            Course one = courseService.getOne(wrapper);
            if (one != null) {
                throw new RunException(REnum.REPETITIVE_NO);
            }
            //查找到教师
            Teacher byId = teacherService.getById(teacherId);
            if (byId == null) {
                throw new RunException(REnum.UNKNOWN_ERROR);
            }
            course.setTeacherNo(byId.getNo());
            courseService.save(course);
            log.info(jsonObject.toJSONString());
            return R.success();
        } catch (Exception e) {
//
//            throw new RunException(REnum.DATA_ERROR);
            throw e;
        }


    }

    /**
     * 输入学生的学号 student_no
     * @return
     */
    @GetMapping("/choose_course")
    public R selectNotChoseCourse(@RequestParam String studentNo){
        List<Map<String, String>> maps = courseService.selectNotChoseCourseByStudentNo(studentNo);
        return R.success(maps);
    }
}
